<!-- CustomerTransactionDialog.vue -->
<template>
    <el-dialog :model-value="visible" :title="targetObject?.name + (isEditMode ? ' 编辑记录' : ' 新建记录')" width="1000px"
        draggable :close-on-click-modal="false" :before-close="handleClose">
        <el-form ref="formRef" :model="transactionOrder" :rules="formRules" label-width="100px" @submit.prevent>
            <el-form-item v-if="!transactionOrder.isPeriodInitial" label="业务日期" prop="operateDateString">
                <el-date-picker v-model="transactionOrder.operateDateString" type="date" placeholder="请选择业务日期"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>

            <el-form-item v-if="!transactionOrder.isPeriodInitial" label="摘要" prop="title">
                <span> {{ transactionOrder.title }} </span>
            </el-form-item>

            <!-- Metal Commodity Fields -->
            <template v-for="(commodity, index) in visibleCommodities" :key="commodity.id">
                <div v-if="!transactionOrder.isPeriodInitial && (visibleSalesCommodities.includes(commodity.id) || visiblePurchaseCommodities.includes(commodity.id))"
                    class="commodity-section">
                    <h4>{{ commodity.standard }} 回购销售</h4>

                    <!-- Sales Group -->
                    <template v-if="visibleSalesCommodities.includes(commodity.id)">
                        <el-row :gutter="10">
                            <el-col :span="8">
                                <el-form-item :label="`销售重量`" :prop="`sales.${commodity.id}.count`">
                                    <input-cell
                                        :model-value="getSalesBatchByCommodityId(commodity.id)?.count?.value ?? ''"
                                        :number-mode="true" :precision="countPrecision" :min="0"
                                        @update:model-value="val => updateSalesCount(commodity.id, val)"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item :label="`销售单价`" :prop="`sales.${commodity.id}.price`">
                                    <input-cell
                                        :model-value="getSalesBatchByCommodityId(commodity.id)?.singlePriceAfterTax?.value ?? ''"
                                        :number-mode="true" :precision="fundPrecision" :min="0"
                                        @update:model-value="val => updateSalesPrice(commodity.id, val)"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item :label="`应收货款`" :prop="`sales.${commodity.id}.total`">
                                    <input-cell
                                        :model-value="getSalesBatchByCommodityId(commodity.id)?.batchPriceWithTax?.value ?? ''"
                                        :number-mode="true" :precision="fundPrecision" :min="0"
                                        @update:model-value="val => { }" style="width: 100%" :readonly="true" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </template>

                    <!-- Purchase Group -->
                    <template v-if="visiblePurchaseCommodities.includes(commodity.id)">
                        <el-row :gutter="10">
                            <el-col :span="8">
                                <el-form-item :label="`回购重量`" :prop="`purchase.${commodity.id}.count`">
                                    <input-cell
                                        :model-value="getPurchaseBatchByCommodityId(commodity.id)?.count?.value ?? ''"
                                        :number-mode="true" :precision="countPrecision" :min="0"
                                        @update:model-value="val => updatePurchaseCount(commodity.id, val)"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item :label="`回购单价`" :prop="`purchase.${commodity.id}.price`">
                                    <input-cell
                                        :model-value="getPurchaseBatchByCommodityId(commodity.id)?.singlePriceAfterTax?.value ?? ''"
                                        :number-mode="true" :precision="fundPrecision" :min="0"
                                        @update:model-value="val => updatePurchasePrice(commodity.id, val)"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item :label="`应付金额`" :prop="`sales.${commodity.id}.total`">
                                    <input-cell
                                        :model-value="getPurchaseBatchByCommodityId(commodity.id)?.batchPriceWithTax?.value ?? ''"
                                        :number-mode="true" :precision="fundPrecision" :min="0"
                                        @update:model-value="val => { }" style="width: 100%" :readonly="true" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </template>
                </div>
            </template>

            <!-- Metal Fund Account Fields -->
            <template v-for="commodity in visibleCommodities" :key="`${commodity.id}_fund`">
                <div v-if="!transactionOrder.isPeriodInitial && (visibleMetalInFundAccounts.includes(commodity.metalAccountTypeId) || visibleMetalOutFundAccounts.includes(commodity.metalAccountTypeId))"
                    class="fund-section">
                    <h4>{{ commodity.standard }} 来料付料</h4>

                    <el-row :gutter="10">
                        <template v-if="visibleMetalInFundAccounts.includes(commodity.metalAccountTypeId)">
                            <el-col :span="8">
                                <el-form-item :label="`来料`" :prop="`metalIn.${commodity.metalAccountTypeId}`">
                                    <input-cell :model-value="getMetalInCount(commodity.metalAccountTypeId)"
                                        :number-mode="true" :precision="countPrecision" :min="0"
                                        @update:model-value="val => updateMetalInCount(commodity.metalAccountTypeId, val)"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </template>

                        <template v-if="visibleMetalOutFundAccounts.includes(commodity.metalAccountTypeId)">
                            <el-col :span="8">
                                <el-form-item :label="`付料`" :prop="`metalOut.${commodity.metalAccountTypeId}`">
                                    <input-cell :model-value="getMetalOutCount(commodity.metalAccountTypeId)"
                                        :number-mode="true" :precision="countPrecision" :min="0"
                                        @update:model-value="val => updateMetalOutCount(commodity.metalAccountTypeId, val)"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </template>
                    </el-row>
                </div>
            </template>

            <!-- Other Fields -->
            <el-row v-if="!transactionOrder.isPeriodInitial" :gutter="10">
                <el-col :span="8">
                    <el-form-item label="来款" prop="receivedAmount">
                        <input-cell :model-value="transactionOrder.receivedAmount?.value ?? ''" :number-mode="true"
                            :precision="fundPrecision" :min="0" @update:model-value="val => updateReceivedAmount(val)"
                            style="width: 100%" />

                    </el-form-item>
                </el-col>
                <el-col v-if="transactionOrder.receivedAmount != null" :span="8">
                    <el-form-item label="收款账户" prop="receivedAccount">
                        <fund-account-select v-model="transactionOrder.fundAccountForReceive" prop="fundAccount"
                            :fund-ui-action="fundUiAction" />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="已付款" prop="paymentAmount">
                        <input-cell :model-value="transactionOrder.paymentAmount?.value ?? ''" :number-mode="true"
                            :precision="fundPrecision" :min="0" @update:model-value="val => updatePaymentAmount(val)"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
                <el-col v-if="transactionOrder.paymentAmount != null" :span="8">
                    <el-form-item label="付款账户" prop="paymentAccount">
                        <fund-account-select v-model="transactionOrder.fundAccountForPayment" prop="fundAccount"
                            :fund-ui-action="fundUiAction" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item v-if="visibleMetalInFundAccounts.includes(MetalFeeTypeDefinition.SwapFee.code)"
                        label="仓息" prop="swapFee">
                        <input-cell :model-value="transactionOrder.swapFee?.fundDouble?.value" :number-mode="true"
                            :precision="fundPrecision" :min="0" @update:model-value="val => updateSwapFee(val)"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- Period Initial Balance Fields -->
            <template v-if="transactionOrder.isPeriodInitial">
                <div class="balance-section">
                    <h4>期初数据</h4>

                    <!-- Metal Balances -->
                    <template v-for="commodity in visibleCommodities" :key="`${commodity.id}_balance`">
                        <div v-if="visibleMetalInFundAccounts.includes(commodity.metalAccountTypeId)"
                            class="metal-balance-item">
                            <el-row :gutter="10">
                                <el-col :span="8">
                                    <el-form-item :label="`存欠${commodity.standard}`"
                                        :prop="`metalBalance.${commodity.metalAccountTypeId}`">
                                        <input-cell :model-value="getMetalBalance(commodity.metalAccountTypeId)"
                                            :number-mode="true" :precision="countPrecision"
                                            @update:model-value="val => updateMetalBalance(commodity.metalAccountTypeId, val)"
                                            style="width: 100%" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </template>

                    <!-- Fund Balance -->
                    <el-row :gutter="10">
                        <el-col :span="8">
                            <el-form-item label="存欠款" prop="balanceAfter">
                                <input-cell :model-value="getBalance()"
                                    :number-mode="true" :precision="fundPrecision"
                                    @update:model-value="val => updateBalanceAfter(val)" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </template>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="transactionOrder.remark" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
        </el-form>



        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    {{ isEditMode ? '更新' : '创建' }}
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ElMessage } from 'element-plus'
import { MetalFeeTypeDefinition } from '../../public/engine/common/metalDefinition.js'
import { CsDouble } from '../../public/engine/common/csDouble.js'
import { CsFundDouble } from '../../public/engine/common/csFundDouble'
import { MetalCombineOrder } from '../../public/engine/metal/metalCombineOrder.js'
import InputCell from '../../public/views/componentsWeb/InputCell.vue'
import FundAccountSelect from '../../public/views/componentsWeb/FundAccountSelect.vue'

export default {
    name: 'CustomerTransactionDialog',
    components: {
        InputCell,
        FundAccountSelect,
    },
    props: {



        metalCommodities: {
            type: Array,
            default: () => []
        },
        visibleSalesCommodities: {
            type: Array,
            default: () => []
        },
        visiblePurchaseCommodities: {
            type: Array,
            default: () => []
        },
        visibleMetalInFundAccounts: {
            type: Array,
            default: () => []
        },
        visibleMetalOutFundAccounts: {
            type: Array,
            default: () => []
        },
        fundPrecision: {
            type: Number,
            default: 2
        },
        countPrecision: {
            type: Number,
            default: 2
        },
        targetObject: {
            type: Object,
            default: () => null
        },
        metalUiAction: {
            type: Object,
            default: () => null
        },
        fundUiAction: {
            type: Object,
            default: () => null
        }
    },
    emits: ['update:visible', 'confirm'],
    data() {
        return {
            MetalFeeTypeDefinition,
            submitting: false,
            transactionOrder: this.getInitialOrderData(),
            formRules: {
                operateDateString: [
                    { required: true, message: '请选择业务日期', trigger: 'change' }
                ]
            },
            visible: false,
            rowData: null,
            isEditMode: false,
        }
    },
    computed: {
        visibleCommodities() {
            return this.metalCommodities.filter(commodity =>
                this.visibleSalesCommodities.includes(commodity.id) ||
                this.visiblePurchaseCommodities.includes(commodity.id) ||
                this.visibleMetalInFundAccounts.includes(commodity.metalAccountTypeId) ||
                this.visibleMetalOutFundAccounts.includes(commodity.metalAccountTypeId)
            )
        }
    },

    methods: {

        showDialog(rowData) {

            this.rowData = rowData
            this.visible = true
            this.isEditMode = !!rowData
            this.resetForm();
        },
        getInitialOrderData() {
            // Create a new MetalCombineOrder instance
            let order = MetalCombineOrder.emptyWithNull(
                { metalCommodities: this.metalCommodities, targetObject: this.targetObject, }
            )

            order.operateDate = new Date();
            return order;
        },

        resetForm() {
            if (this.isEditMode && this.rowData) {
                // Clone the existing row data for editing
                // console.log("this.rowData:", this.rowData);
                this.transactionOrder = MetalCombineOrder.clone(this.rowData)


                // console.log("resetFom clone exist order:", this.transactionOrder);               
            } else {
                // Initialize empty order for new record
                this.transactionOrder = this.getInitialOrderData()
            }

        },

        // Helper methods to get batch data
        getSalesBatchByCommodityId(commodityId) {
            return this.transactionOrder.getSalesBatchByCommodityId(commodityId)
        },

        getPurchaseBatchByCommodityId(commodityId) {
            return this.transactionOrder.getPurchaseBatchByCommodityId(commodityId)
        },

        getMetalInCount(metalAccountTypeId) {
            const fundAccount = this.transactionOrder.getMetalBalanceByMetalFoundTypeId(metalAccountTypeId)
            return fundAccount ? fundAccount.inCount?.value : 0
        },

        getMetalOutCount(metalAccountTypeId) {
            const fundAccount = this.transactionOrder.getMetalBalanceByMetalFoundTypeId(metalAccountTypeId)
            return fundAccount?.outCount?.value ?? ''
        },

        // New methods for balance fields
        getMetalBalance(metalAccountTypeId) {
            const fundAccount = this.transactionOrder.getMetalBalanceByMetalFoundTypeId(metalAccountTypeId)
            return  fundAccount?.innerBalance?.value ?? ""
        },

        getBalance(){
            console.log('getBalance',this.transactionOrder);
            return this.transactionOrder?.innerBalance?.value ?? '';
        },

        // Update methods for sales data
        updateSalesCount(commodityId, value) {
            const batch = this.transactionOrder.getSalesBatchByCommodityId(commodityId)

            batch.setCount(new CsDouble(value, this.countPrecision))
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        updateSalesPrice(commodityId, value) {
            const batch = this.transactionOrder.getSalesBatchByCommodityId(commodityId)

            batch.setSinglePriceAfterTax(new CsFundDouble(value, this.fundPrecision))
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        // Update methods for purchase data
        updatePurchaseCount(commodityId, value) {
            const batch = this.transactionOrder.getPurchaseBatchByCommodityId(commodityId)

            batch.setCount(new CsDouble(value, this.countPrecision))
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        updatePurchasePrice(commodityId, value) {
            const batch = this.transactionOrder.getPurchaseBatchByCommodityId(commodityId)

            batch.setSinglePriceAfterTax(new CsFundDouble(value, this.fundPrecision))
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        // Update methods for metal fund accounts
        updateMetalInCount(metalAccountTypeId, value) {
            const fundAccount = this.transactionOrder.getMetalBalanceByMetalFoundTypeId(metalAccountTypeId)

            fundAccount.inCount = new CsDouble(value, this.countPrecision)
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        updateMetalOutCount(metalAccountTypeId, value) {
            const fundAccount = this.transactionOrder.getMetalBalanceByMetalFoundTypeId(metalAccountTypeId)

            fundAccount.outCount = new CsDouble(value, this.countPrecision)
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        // Update methods for other fields
        updateReceivedAmount(value) {
            if (value !== null) {
                this.transactionOrder.receivedAmount = new CsFundDouble(value, this.fundPrecision)
            } else {
                this.transactionOrder.receivedAmount = null
            }
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        updatePaymentAmount(value) {
            if (value !== null) {
                this.transactionOrder.paymentAmount = new CsFundDouble(value, this.fundPrecision)
            } else {
                this.transactionOrder.paymentAmount = null
            }
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        updateSwapFee(value) {
            if (value !== null) {
                this.transactionOrder.swapFee.fundDouble = new CsFundDouble(value, this.fundPrecision)
            } else {
                this.transactionOrder.swapFee.fundDouble = null
            }
            this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        updateMetalBalance(metalAccountTypeId, value) {
            const fundAccount = this.transactionOrder.getMetalBalanceByMetalFoundTypeId(metalAccountTypeId)
            if (fundAccount) {
                 console.log('found MetalBalance');
                fundAccount.innerBalance = new CsDouble(value, this.countPrecision)
                //this.transactionOrder.updateOrderInfo(this.metalCommodities);
            }
            else {
                console.log('error: updateMetalBalance fundAccount is null');
            }
        },

         updateBalanceAfter(value) {
            if (value !== null) {
                this.transactionOrder.innerBalance = new CsFundDouble(value, this.fundPrecision)
            } else {
                this.transactionOrder.innerBalance = null
            }
            //this.transactionOrder.updateOrderInfo(this.metalCommodities);
        },

        handleClose() {
            this.visible = false;
            this.$emit('update:visible', false)
        },

        async handleSubmit() {
            try {
                this.submitting = true

                let ret = this.transactionOrder.validateOrder();

                if (ret) {
                    ElMessage.error(ret.errorMsg);
                    return;
                }

                try {

                    const orderResult = await this.metalUiAction.updateMetalCombineOrderBatch({
                        orders: [this.transactionOrder.toJson()],
                    });

                    if (orderResult) {
                        ElMessage.success("提交保存成功");
                    }

                } catch (error) {
                    console.error('保存数据失败:', error);
                    ElMessage.error('数据保存失败: ' + (error.message || '未知错误'));
                    return;
                }


                // Emit confirm event with the prepared data
                this.$emit('confirm')

                // Close dialog
                this.handleClose()

                ElMessage.success(this.isEditMode ? '更新成功' : '创建成功')
            } catch (error) {
                console.error('Form validation error:', error)
                if (error !== false) {
                    ElMessage.error('请检查表单填写是否正确')
                }
            } finally {
                this.submitting = false
            }
        }
    }
}
</script>

<style scoped>
.commodity-section,
.fund-section {
    border-bottom: 1px solid #ebeef5;
    padding: 10px 0;
    margin-bottom: 10px;
}

.commodity-section h4,
.fund-section h4 {
    margin: 0 0 10px 0;
    color: #606266;
    font-size: 14px;
    font-weight: 500;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.balance-section h4 {
    margin: 0 0 10px 0;
    color: #606266;
    font-size: 14px;
    font-weight: 500;
}

.metal-balance-item {
    margin-bottom: 10px;
}
</style>